package cn.toolck.controller;

import cn.toolck.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Value("${test}")
    public String testStr;

    /**
     * 注册接⼝
     *
     * @param email    邮箱
     * @param password 密码
     * @param code     验证码
     * @return true成功，false失败
     */
    @GetMapping("/register/{email}/{password}/{code}")
    public int register(
            @PathVariable("email") String email
            , @PathVariable("password") String password
            , @PathVariable("code") String code) {
        return userService.register(email, password, code);
    }

    /**
     * 是否已注册
     *
     * @param email 邮箱
     * @return rue代表已经注册过，false代表尚未注册
     */
    @GetMapping("/isRegistered/{email}")
    public boolean isRegistered(@PathVariable("email") String email) {
        return userService.isRegistered(email);
    }

    /**
     * 登录接⼝，验证⽤户名密码合法性，根据⽤户名和
     * 密码⽣成token，token存⼊数据库，并写⼊cookie
     * 中，登录成功返回邮箱地址，重定向到欢迎⻚
     *
     * @param email 邮箱
     * @return 邮箱地址
     */
    @GetMapping("/login/{email}/{password}")
    public String login(@PathVariable("email") String email
            , @PathVariable("password") String password
            , HttpServletResponse response) {
        if (userService.login(email, password, response)) {
            return email;
        }
        System.err.println(testStr);
        return "false";
    }

    /**
     * 根据token查询⽤户登录邮箱接⼝
     *
     * @param token token
     * @return 邮箱
     */
    @GetMapping("/info/{token}")
    public String info(@PathVariable("token") String token) {
        return userService.info(token);
    }

}
